package com.shujia.scala

import scala.io.Source

object Demo24Student {
  def main(args: Array[String]): Unit = {

    /**
      * 1、统计排名前十学生各科的分数 [学号,学生姓名，学生班级，科目名，分数]
      *
      */

    //1|统计学生的总分

    val score = Source.fromFile("scala/data/score.txt").getLines().toList
    val cource = Source.fromFile("scala/data/cource.txt").getLines().toList
    val student = Source.fromFile("scala/data/students.txt").getLines().toList


    //取出学号和分数
    val kvScore = score.map(line => {
      val split = line.split(",")
      val id = split(0)
      val sco = split(2).toInt

      (id, sco)
    })


    //通过学号进行分组
    val groupByScore = kvScore.groupBy(kv => kv._1)


    val sumScore = groupByScore.map(kv => {
      val id = kv._1

      //统计学生总分
      val sumScore = kv._2.map(v => v._2).sum

      (id, sumScore)
    }).toList

    //按照总分进行降序排序
    val sortScore = sumScore.sortBy(kv => -kv._2)

    //取top10

    val top10 = sortScore.take(10).map(kv => kv._1)


    /**
      * 实现表关联
      *
      *
      */

    //将学生表和科目表转换成map集合

    val kvStudent = student.map(line => {
      val split = line.split(",")

      val id = split(0)
      val name = split(1)
      val clazz = split(4)


      (id, name + "\t" + clazz)
    }).toMap //当list是一个kv  格式的时候可以直接转换成一个map集合

    val kvCource = cource.map(line => {
      val split = line.split(",")

      val id = split(0)
      val name = split(1)

      (id, name)
    }).toMap //当list是一个kv  格式的时候可以直接转换成一个map集合


    //先过滤再关联


    val filterScore = score.filter(line => {
      val id = line.split(",")(0)

      top10.contains(id)
    })

    //关联   [学号,学生姓名，学生班级，科目名，分数]
    val result = filterScore.map(line => {
      val split = line.split(",")
      val id = split(0)

      val couId = split(1)

      val sco = split(2)

      //通过学号取出学生信息
      val nameAndClazz = kvStudent(id)


      //取出科目名
      val couName = kvCource(couId)


      id + "\t" + nameAndClazz + "\t" + couName + "\t" + sco
    })


    result.foreach(println)

  }

}
